package com.xqq.juc;

import java.util.concurrent.*;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadPoolDebugger {
    private static final AtomicInteger taskCounter = new AtomicInteger(0);
    private static final AtomicInteger threadCounter = new AtomicInteger(0);

    // 定义线程池状态常量
    private static final int RUNNING    = -1 << 29;
    private static final int SHUTDOWN   =  0 << 29;
    private static final int STOP       =  1 << 29;
    private static final int TIDYING    =  2 << 29;
    private static final int TERMINATED =  3 << 29;

    public static void main(String[] args) throws Exception {
        // 创建可调试线程池
        DebuggableThreadPoolExecutor executor = new DebuggableThreadPoolExecutor(
                2, // 核心线程数
                4, // 最大线程数
                30, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(2), // 任务队列容量
                new CustomThreadFactory(), // 自定义线程工厂
                new CustomRejectedExecutionHandler() // 自定义拒绝策略
        );

        System.out.println("===== 线程池调试程序启动 =====");
        executor.printPoolState("初始状态");

        // 提交10个任务
        for (int i = 0; i < 10; i++) {
            executor.execute(new Task());
            Thread.sleep(100); // 控制提交速度
            executor.printPoolState("提交任务-" + (i + 1) + "后");
        }

        // 监控线程
        Thread monitorThread = new Thread(() -> {
            while (!executor.isTerminated()) {
                executor.printPoolState("监控状态");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
            System.out.println("监控线程结束");
        });
        monitorThread.setDaemon(true);
//        monitorThread.start();

        // 关闭线程池
        Thread.sleep(5000);
        System.out.println("\n===== 关闭线程池 =====");
        executor.shutdown();

        // 等待线程池终止
        executor.awaitTermination(10, TimeUnit.SECONDS);
        executor.printPoolState("最终状态");
    }

    // 自定义任务
    static class Task implements Runnable {
        private final int id = taskCounter.incrementAndGet();

        @Override
        public void run() {
            System.out.printf("[%tT] 任务-%d 开始执行 (线程: %s)\n",
                    System.currentTimeMillis(), id, Thread.currentThread().getName());
            try {
                // 模拟任务执行时间
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.printf("[%tT] 任务-%d 完成\n", System.currentTimeMillis(), id);
        }

        @Override
        public String toString() {
            return "Task-" + id;
        }
    }

    // 自定义线程工厂
    static class CustomThreadFactory implements ThreadFactory {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "Pool-Thread-" + threadCounter.incrementAndGet());
            t.setUncaughtExceptionHandler((thread, ex) -> {
                System.err.printf("[%tT] 线程 %s 异常: %s\n",
                        System.currentTimeMillis(), thread.getName(), ex.getMessage());
            });
            return t;
        }
    }

    // 自定义拒绝策略
    static class CustomRejectedExecutionHandler implements RejectedExecutionHandler {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            System.err.printf("[%tT] 任务被拒绝: %s\n", System.currentTimeMillis(), r);
            System.err.println("当前线程池状态:");
            if (executor instanceof DebuggableThreadPoolExecutor) {
                ((DebuggableThreadPoolExecutor) executor).printPoolState("拒绝任务时");
            }
        }
    }

    // 可调试的线程池实现
    static class DebuggableThreadPoolExecutor extends ThreadPoolExecutor {
        private final ReentrantLock debugLock = new ReentrantLock();

        public DebuggableThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,
                                            TimeUnit unit, BlockingQueue<Runnable> workQueue,
                                            ThreadFactory threadFactory,
                                            RejectedExecutionHandler handler) {
            super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
        }

        // 打印线程池状态
        public void printPoolState(String context) {
            debugLock.lock();
            try {
                // 获取内部状态字段
                Field ctlField = ThreadPoolExecutor.class.getDeclaredField("ctl");
                ctlField.setAccessible(true);
                AtomicInteger ctl = (AtomicInteger) ctlField.get(this);

                Field workersField = ThreadPoolExecutor.class.getDeclaredField("workers");
                workersField.setAccessible(true);
                @SuppressWarnings("unchecked")
                Set<Object> workers = (Set<Object>) workersField.get(this);

                // 解析ctl值
                int c = ctl.get();
                int workerCount = workerCountOf(c);
                int runState = runStateOf(c);

                // 获取任务队列
                BlockingQueue<Runnable> queue = getQueue();

                // 打印状态信息
                System.out.printf("\n===== [%s] =====\n", context);
                System.out.println("运行状态: " + getStateName(runState));
                System.out.println("核心线程数: " + getCorePoolSize());
                System.out.println("最大线程数: " + getMaximumPoolSize());
                System.out.println("工作线程数: " + workerCount);
                System.out.println("活动线程数: " + getActiveCount());
                System.out.println("任务队列大小: " + queue.size());
                System.out.println("已完成任务数: " + getCompletedTaskCount());
                System.out.println("总任务数: " + getTaskCount());
                System.out.println("池大小历史峰值: " + getLargestPoolSize());

                // 打印工作线程状态
                System.out.println("\n工作线程详情:");
                int index = 0;
                for (Object worker : workers) {
                    Class<?> workerClass = worker.getClass();

                    Field threadField = workerClass.getDeclaredField("thread");
                    threadField.setAccessible(true);
                    Thread thread = (Thread) threadField.get(worker);

                    Field taskField = workerClass.getDeclaredField("firstTask");
                    taskField.setAccessible(true);
                    Runnable task = (Runnable) taskField.get(worker);

                    Field completedTasksField = workerClass.getDeclaredField("completedTasks");
                    completedTasksField.setAccessible(true);
                    long completedTasks = completedTasksField.getLong(worker);

                    System.out.printf("  Worker-%d: 线程=%s 状态=%s 任务=%s 完成任务数=%d\n",
                            index++,
                            thread.getName(),
                            thread.getState(),
                            task != null ? task.toString() : "null",
                            completedTasks);
                }

                // 打印任务队列内容
                System.out.println("\n任务队列内容:");
                if (queue.isEmpty()) {
                    System.out.println("  (空)");
                } else {
                    int i = 0;
                    for (Runnable r : queue) {
                        System.out.printf("  [%d] %s\n", i++, r.toString());
                    }
                }

            } catch (Exception e) {
                System.err.println("状态获取失败: " + e.getMessage());
            } finally {
                debugLock.unlock();
            }
        }

        // 从ctl中提取工作线程数
        private int workerCountOf(int c) {
            return c & 0x1FFFFFFF; // 低29位
        }

        // 从ctl中提取运行状态
        private int runStateOf(int c) {
            return c & ~0x1FFFFFFF; // 高3位
        }

        // 获取状态名称
        private String getStateName(int runState) {
            if (runState == RUNNING) return "RUNNING";
            if (runState == SHUTDOWN) return "SHUTDOWN";
            if (runState == STOP) return "STOP";
            if (runState == TIDYING) return "TIDYING";
            if (runState == TERMINATED) return "TERMINATED";
            return "UNKNOWN";
        }

        // 覆盖关键方法添加日志
        @Override
        public void execute(Runnable command) {
            System.out.printf("\n[%tT] 提交任务: %s\n", System.currentTimeMillis(), command);
            super.execute(command);
        }

        @Override
        protected void beforeExecute(Thread t, Runnable r) {
            System.out.printf("[%tT] 线程 %s 开始执行任务: %s\n",
                    System.currentTimeMillis(), t.getName(), r);
        }

        @Override
        protected void afterExecute(Runnable r, Throwable t) {
            System.out.printf("[%tT] 线程 %s 完成任务: %s\n",
                    System.currentTimeMillis(), Thread.currentThread().getName(), r);
            if (t != null) {
                System.err.printf("[%tT] 任务执行异常: %s\n", System.currentTimeMillis(), t.getMessage());
            }
        }

        @Override
        protected void terminated() {
            System.out.printf("\n[%tT] 线程池终止\n", System.currentTimeMillis());
            super.terminated();
        }
    }
}